package com.macro.mall.tiny.security.interceptor;

import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import com.macro.mall.tiny.security.util.MemberContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tyrone
 * @date 2024/10/15 00:21
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String TOKEN_KEY = "MemberToken";

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UmsMemberService umsMemberService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN_KEY);
        if (StringUtils.isEmpty(token)){
            return true;
        }
        token=token.substring(tokenHead.length());
        if (!ObjectUtils.isEmpty(token)) {
            if (jwtTokenUtil.isTokenExpired(token)) return false;
            Long memberId = Long.valueOf(jwtTokenUtil.getUserNameFromToken(token));
            UmsMember um = umsMemberService.getUmsMemberById(memberId);
            MemberContext.setMember(um);
            return true;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MemberContext.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
